import { loginData, safeout, checkLogin } from 'api/user'

export default {
  namespaced: true,
  state: {
    isLogin: localStorage.getItem('isLogin') ? localStorage.getItem('isLogin') : false,
    uid: localStorage.getItem('uid') ? localStorage.getItem('uid') : '',
    nickname: localStorage.getItem('nickname') ? localStorage.getItem('nickname') : '',
    authToken: localStorage.getItem('authToken') ? localStorage.getItem('authToken') : ''
  },
  mutations: {
    // 保存登陆
    ['SET_LOGIN'] (state, payload) {
      state.isLogin = true
      state.uid = payload.uid
      state.nickname = payload.nickname
      state.authToken = payload.authToken
      localStorage.setItem('isLogin', true)
      localStorage.setItem('uid', payload.uid)
      localStorage.setItem('nickname', payload.nickname)
      localStorage.setItem('authToken', payload.authToken)
    },
    // 退出登录
    ['OUT_LOGIN'] (state) {
      state.isLogin = false
      state.uid = ''
      state.nickname = ''
      state.authToken = ''
      localStorage.removeItem('isLogin')
      localStorage.removeItem('uid')
      localStorage.removeItem('nickname')
      localStorage.removeItem('authToken')
      sessionStorage.removeItem('addsid')
    }

  },
  actions: {
    // 登录
    login (context, payload) {
      if (payload.cellphone && payload.password) {
        loginData(payload.cellphone, payload.password).then(res => {
          if (res.code === 200) {
            context.commit('SET_LOGIN', {
              uid: res.data.uid,
              nickname: res.data.nickname,
              authToken: res.data.auth_token,
            })
          }
          payload.success && payload.success(res)
        })
      }
    },
    //退出登录
    logout (context) {
      return safeout(context.state.uid).then(res => {
        if (res.code === 200) {
          context.commit('OUT_LOGIN')
        }
        return res
      })
    },
    //验证登录
    loginCheck (context) {
      return checkLogin(context.state.uid, context.state.authToken).then(res => {
        if (res.code === 200) {
          return true
        } else {
          context.commit('OUT_LOGIN')
          return false
        }
      })
    }
  }
}
